#!/usr/bin/env python3

# -*- coding: utf-8 -*-
# File Name: log.py
# Author: bobo
# Created Time: 20241208

import logging
from logging import StreamHandler
from logging.handlers import RotatingFileHandler

global LOG_LEVEL
LOG_LEVEL = logging.DEBUG
LOG_DIR = "/tmp"
# 设置日志输出格式
LOG_FORMATTER = logging.Formatter(
    "%(asctime)s-%(module)s.%(name)s.%(funcName)s-%(filename)s:%(lineno)d-%(levelname)s: %(message)s"
)


def get_logger(
    name: str = "main_log", level=None, formatter=LOG_FORMATTER
) -> logging.Logger:
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # 创建一个Handler来将日志输出到控制台
    console_handler = StreamHandler()
    # 控制台仅记录INFO及以上级别的日志
    console_handler.setLevel(level or LOG_LEVEL)
    console_handler.setFormatter(formatter)

    # 将处理器添加到日志记录器中
    logger.addHandler(console_handler)

    return logger


def add_file_handler(
    logger: logging.Logger, level=None, formatter=LOG_FORMATTER
) -> logging.Logger:
    # 创建RotatingFileHandler对象，设置日志输出路径、最大文件大小和备份数量
    file_handler = RotatingFileHandler(
        f"{LOG_DIR}/{logger.name}.log", maxBytes=1024 * 1024, backupCount=3
    )
    # 设置日志级别和输出格式
    file_handler.setLevel(level or LOG_LEVEL)
    file_handler.setFormatter(formatter)

    # 将处理器添加到日志记录器中
    logger.addHandler(file_handler)

    return logger


def set_level(level):
    global LOG_LEVEL
    LOG_LEVEL = level
    # 获取当前管理器中的所有日志器
    current_loggers = logging.Logger.manager.loggerDict

    # 打印当前创建的所有日志器
    for name, logger in current_loggers.items():
        logger.setLevel(level)
